import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { useUserStore } from './user'
import { getCartListApi, add2CartApi, remProductApi, mergeCartApi, saveSelectApi } from '@/api/shoppingCart'
// const userStore = useUserStore() // 报错

export const useLocalCartStore = defineStore(
  'localCart',
  () => {
    //1. state
    const cartList = ref([])

    //2. getters
    // 商品总数
    const productCount = computed(() => cartList.value.length)
    // 商品总价
    const productTotal = computed(() => cartList.value.reduce((r, i) => r + i.count * i.price, 0))

    // 商品是否全都被选中
    const isAllSeleted = computed(() => cartList.value.every((i) => i.selected === true))

    // 计算选中商品的数量
    const selectedProductCount = computed(() => {
      let count = 0
      cartList.value.forEach((i) => {
        if (i.selected) {
          count++
        }
      })
      return count
    })

    // 计算选中商品的总价
    const selectedProductTotal = computed(() => {
      let total = 0
      cartList.value.forEach((i) => {
        if (i.selected) {
          total += i.count * i.price
        }
      })
      return total
    })

    //3. actions
    // 调用接口获取并设置购物车列表
    const setCartList = async () => {
      const res = await getCartListApi()
      cartList.value = res.result
    }

    // 合并本地购物车和服务器购物车
    const mergeCart = async () => {
      await mergeCartApi(
        cartList.value.map((i) => {
          return { skuId: i.skuId, selected: i.selected, count: i.count }
        })
      )
    }

    // 加入购物车
    const add2Cart = async (product) => {
      const userStore = useUserStore()
      if (userStore.token) {
        // 发送请求加入购物车
        await add2CartApi(product)

        // 获取购物车列表，并覆盖之前的购物车
        setCartList()
      } else {
        const item = cartList.value.find((i) => i.skuId === product.skuId)
        // 如果已存在购物车中则加上加入的数量，否则直接加入
        if (item) {
          item.count += product.count
        } else {
          cartList.value.push(product)
        }
      }
    }

    // 删除购物车中某件商品
    const delCart = async (skuIds) => {
      const userStore = useUserStore()
      if (userStore.token) {
        await remProductApi({ ids: skuIds })
        // 获取购物车列表，并覆盖之前的购物车
        setCartList()
      } else {
        cartList.value = cartList.value.filter((i) => !skuIds.includes(i.skuId))
      }
    }

    // 选中购物车中的某件商品
    const seleteProduct = (skuId, flag) => {
      cartList.value.forEach((i) => {
        if (i.skuId === skuId) {
          i.selected = flag
        }
      })
    }

    // 全选或全反选购物车中的所有商品
    const seleteAllProduct = (flag) => {
      cartList.value.forEach((i) => {
        i.selected = flag
      })
    }

    // 将选中状态提交给后端保存
    const saveSelectStatus = async () => {
      const selectedIds = []
      const unSelectedIds = []

      cartList.value.forEach((i) => {
        if (i.selected) {
          selectedIds.push(i.skuId)
        } else {
          unSelectedIds.push(i.skuId)
        }
      })

      if (selectedIds.length > 0) {
        await saveSelectApi({ selected: true, ids: selectedIds })
      }
      if (unSelectedIds.length > 0) {
        await saveSelectApi({ selected: false, ids: unSelectedIds })
      }
    }

    // 清空购物车
    const clearCart = () => {
      cartList.value = []
    }

    return {
      cartList,
      productCount,
      productTotal,
      isAllSeleted,
      selectedProductCount,
      selectedProductTotal,
      setCartList,
      mergeCart,
      add2Cart,
      delCart,
      seleteProduct,
      seleteAllProduct,
      clearCart,
      saveSelectStatus
    }
  },
  { persist: true }
)
